package com.zxmclasslibrarie.network.req;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import android.util.Log;

public class HttpPostTool {

	public static String post(String url, Map<String, String> params) {
		HttpClient client = HttpClientSingleton.generateHttpClient();

		HttpPost post = new HttpPost(url);
		HttpResponse response = null;
		String jsonString = null;
		HttpEntity responseEntity = null;
		try {
			if (null != params) {
				List<NameValuePair> requestEntity = new ArrayList<NameValuePair>();

				for (String key : params.keySet()) {
					NameValuePair nameValuePair = new BasicNameValuePair(key,
							params.get(key));
					requestEntity.add(nameValuePair);
				}
				UrlEncodedFormEntity entity = new UrlEncodedFormEntity(
						requestEntity, "utf-8");
				post.setEntity(entity);
			}
			response = client.execute(post);
			if (null != response
					&& response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
				responseEntity = response.getEntity();
				if (null != responseEntity) {
					jsonString = EntityUtils.toString(responseEntity);
				}
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				if (null != responseEntity)
					responseEntity.consumeContent();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		Log.w("zhaole", "zhaole:" + jsonString);
		return jsonString;
	}

}
